import React, { ReactNode, useRef, useState } from "react"

const AuthContext = React.createContext<{user: any; login: any; logout: any} | undefined>(undefined)
AuthContext.displayName = 'AuthContext'

export const AuthProvider = ({ children }: { children: ReactNode}) => {
  const [user, setUser] = useState<{ name: string; token: string;} | null>(null)
  const providerRef = useRef<{user: any; login: any; logout: any}>()
  const login = ()  => {
    console.log('login...')
    setUser({ name: 'xxx', token: 'xxxxxx' })
  }
  const logout = () => {
    setUser({ name: '', token: '' })
    console.log('logout')
  }
  console.log('AuthProvider=======>')

  return <AuthContext.Provider value={{ user, login, logout }}>
    { children }
  </AuthContext.Provider>
}

export const useAuth = () => {
  const context = React.useContext(AuthContext)
  if (!context) {
    throw new Error('useAuth must in auth provider')
  }
  return context
}